﻿using KwaiXiaoDian.Entity.Common;
using KwaiXiaoDian.Entity.DO;
using KwaiXiaoDian.Entity.VO.GroupLeader;
using KwaiXiaoDian.Entity.VO.Product;
using KwaiXiaoDian.IDao;
using KwaiXiaoDian.IService;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using RestSharp;
using SSharing.Frameworks.NetCore.Common.Consts;
using SSharing.Frameworks.NetCore.Common.Extends;
using SSharing.Frameworks.NetCore.Common.Results;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace KwaiXiaoDian.Service
{
    /// <summary>
    /// 快小店service
    /// </summary>
    public class KwaiXiaoDianService : IKwaiXiaoDianService
    {
        private readonly IConfiguration _configuration;
        private readonly ICookieDao _cookieDao;
        private readonly IMemoryCache _memoryCache;

        public KwaiXiaoDianService(IConfiguration configuration
            , ICookieDao cookieDao
            , IMemoryCache memoryCache)
        {
            _configuration = configuration;
            _cookieDao = cookieDao;
            _memoryCache = memoryCache;
        }

        /// <summary>
        /// 获取团长信息，输入:团长名称或团长id，输出：团长信息列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public IList<GroupLeaderInfo> GetGroupLeaderInfo(GetGroupLeaderInfoRequest getGroupLeaderInfoRequest)
        {
            //https://app.kwaixiaodian.com/gateway/distribute/app/investment/activity/user/list
            //获取cookie
            IList<GroupLeaderInfo> groupLeaders = new List<GroupLeaderInfo>();
            var now = DateTime.Now;

            var kwaiXiaoDianSection = _configuration.GetSection("KwaiXiaoDian");
            var kwaiXiaoDianHost = kwaiXiaoDianSection["ApiHost"].TrimEnd('/');
            var cookies = _cookieDao.Get(p => p.Domain == Consts.Domains.KwaiXiaoDian);
            if (!cookies.HasValue())
            {
                return groupLeaders;
            }

            //构造POST请求，调用快手api
            var requestUrl = @"/gateway/distribute/app/investment/activity/user/list";

            //分页获取团长信息，通过pcursor参数遍历全部团长信息
            var pcursor = "0";
            do
            {
                //使用HttpClient实现
                var baseAddress = new Uri(kwaiXiaoDianHost);
                using (var client = new HttpClient() { BaseAddress = baseAddress, Timeout = TimeSpan.FromSeconds(180) })
                {
                    //添加request header
                    client.DefaultRequestHeaders.Add("Host", "app.kwaixiaodian.com");
                    client.DefaultRequestHeaders.Add("Accept", "application/json, text/plain, */*");
                    client.DefaultRequestHeaders.Add("kpf", "IPHONE_H5");
                    client.DefaultRequestHeaders.Add("Sec-Fetch-Site", "same-origin");
                    client.DefaultRequestHeaders.Add("kpn", "undefined");
                    client.DefaultRequestHeaders.Add("Accept-Language", "zh-CN,zh-Hans;q=0.9");
                    client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate, br");
                    client.DefaultRequestHeaders.Add("Sec-Fetch-Mode", "cors");
                    client.DefaultRequestHeaders.Add("Trace-Id", "1.0.0.1739002116097.16");
                    client.DefaultRequestHeaders.Add("Origin", "https://app.kwaixiaodian.com");
                    client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 17_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Kwai/13.0.10.9095 MerchantWeb/1.0 ISLP/0 StatusHT/47 KDT/PHONE iosSCH/0 TitleHT/44 NetType/WIFI ISDM/0 ICFO/0 locale/zh-Hans CT/0 Yoda/3.0.7 ISLB/0 CoIS/2 ISLM/0 WebViewType/WK BHT/102 AZPREFIX/az2");
                    client.DefaultRequestHeaders.Add("Referer", "https://app.kwaixiaodian.com/page/kwaishop-cps-hybrid/recommend/leader/landing?layoutType=4&_refer=https%3A%2F%2Fapp.kwaixiaodian.com%2Fpage%2Fkwaishop-cps-hybrid%2Frecommend%2Fleader%2Fleader-goods");
                    //client.DefaultRequestHeaders.Add("Content-Length", "97");
                    client.DefaultRequestHeaders.Add("Connection", "keep-alive");
                    //client.DefaultRequestHeaders.Add("Content-Type", "application/x-www-form-urlencoded");
                    client.DefaultRequestHeaders.Add("Sec-Fetch-Dest", "empty");

                    //添加cookie，将 Cookie 信息作为一个字符串添加到请求头的 Cookie 字段中
                    var sbCookie = new StringBuilder();
                    foreach (var cookie in cookies)
                    {
                        sbCookie.AppendFormat("{0}={1}; ", cookie.Name, cookie.Value);
                    }
                    var cookieStr = sbCookie.ToString().TrimEnd(';').TrimEnd(' ');
                    client.DefaultRequestHeaders.Add("Cookie", cookieStr);

                    //设置请求体
                    var keyWord = !getGroupLeaderInfoRequest.Name.IsNullOrEmpty() ? getGroupLeaderInfoRequest.Name : getGroupLeaderInfoRequest.Id;
                    var dicRequestBody = new Dictionary<string, string>();
                    dicRequestBody.Add("keyWord", keyWord);
                    dicRequestBody.Add("channelId", "99");
                    dicRequestBody.Add("orderFiled", "6");
                    dicRequestBody.Add("orderType", "1");
                    dicRequestBody.Add("pcursor", pcursor);
                    dicRequestBody.Add("activityUserLevelList", "");
                    var content = new FormUrlEncodedContent(dicRequestBody);
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

                    GetGroupLeaderInfoResponse getGroupLeaderInfoResponse = null;
                    var response = client.PostAsync(requestUrl, content).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        Task<byte[]> t = response.Content.ReadAsByteArrayAsync();
                        if (t != null)
                        {
                            getGroupLeaderInfoResponse = t.Result.GZipDecompress().FromJson<GetGroupLeaderInfoResponse>();
                        }
                    }

                    if (getGroupLeaderInfoResponse == null
                        || getGroupLeaderInfoResponse.result != 1
                        || getGroupLeaderInfoResponse.data.recoPromotions.Length == 0)
                    {
                        break;
                    }

                    var recoPromotions = getGroupLeaderInfoResponse.data.recoPromotions.ToList();
                    foreach (var recoPromotion in recoPromotions)
                    {
                        var avgCommissionRateThirtyDays = 0.00m;
                        var productAvgpriceThirtyDays = 0.00m;

                        //平均佣金率
                        if (!recoPromotion.avgCommissionRate30DayFuzzy.IsNullOrEmpty())
                        {
                            avgCommissionRateThirtyDays = recoPromotion.avgCommissionRate30DayFuzzy.TrimEnd('%').ToDecimal() / 100;
                        }

                        //商品均价
                        if (!recoPromotion.itemAvgPrice30D.IsNullOrEmpty())
                        {
                            productAvgpriceThirtyDays = recoPromotion.itemAvgPrice30D.TrimEnd('元').ToDecimal();
                        }

                        groupLeaders.Add(new GroupLeaderInfo
                        {
                            LeaderId = recoPromotion.promotionId.ToString(),
                            Name = recoPromotion.promotionNick,
                            IconUrl = recoPromotion.promotionIconUrl,
                            Channel = string.Join(",", recoPromotion.hotSaleChannelList),
                            ProductCountThirtyDays = recoPromotion.promotionItemCount30DayFuzzy.ToIntOrNullAllowThousands(),
                            PromoterCountThirtyDays = recoPromotion.promotionPromoterCount30DayFuzzy.ToIntOrNullAllowThousands(),
                            AvgCommissionRateThirtyDays = avgCommissionRateThirtyDays,
                            ProductAvgpriceThirtyDays = productAvgpriceThirtyDays,
                            ProductCount = recoPromotion.itemCountFuzzy.ToIntOrNullAllowThousands()
                        });
                    }

                    //设置pcursor
                    pcursor = getGroupLeaderInfoResponse.data.pcursor;

                    //每个请求之间间隔
                    Thread.Sleep(500);
                }
            } while (pcursor != "" && pcursor != "no_more");

            return groupLeaders;
        }

        /// <summary>
        /// 获取商品信息，输入：团长id，输出：商品信息列表
        /// </summary>
        /// <param name="leaderId"></param>
        /// <returns></returns>
        public ApiResult<IList<TProduct>> GetProductInfo(string leaderId, long channelId = 99, int millisecondsTimeout = 500)
        {
            //https://app.kwaixiaodian.com/distribute/wireless/selection/home/queryItemList
            ApiResult<IList<TProduct>> apiResult = new ApiResult<IList<TProduct>>();
            IList<TProduct> products = new List<TProduct>();
            var now = DateTime.Now;

            var kwaiXiaoDianSection = _configuration.GetSection("KwaiXiaoDian");
            var kwaiXiaoDianHost = kwaiXiaoDianSection["ApiHost"].TrimEnd('/');
            var cookies = _cookieDao.Get(p => p.Domain == Consts.Domains.KwaiXiaoDian);
            if (!cookies.HasValue())
            {
                apiResult.ErrorMessage = "从数据库未获取到cookie！";
                return apiResult;
            }

            //构造POST请求，调用快手api
            var requestUrl = @"/distribute/wireless/selection/home/queryItemList";

            //分页获取商品信息，通过pcursor参数遍历全部商品
            var pcursor = "";
            do
            {
                //使用HttpClient实现
                var baseAddress = new Uri(kwaiXiaoDianHost);
                using (var client = new HttpClient() { BaseAddress = baseAddress, Timeout = TimeSpan.FromSeconds(180) })
                {
                    //添加request header
                    client.DefaultRequestHeaders.Add("Host", "app.kwaixiaodian.com");
                    client.DefaultRequestHeaders.Add("Accept", "application/json, text/plain, */*");
                    client.DefaultRequestHeaders.Add("kpf", "IPHONE_H5");
                    client.DefaultRequestHeaders.Add("Sec-Fetch-Site", "same-origin");
                    client.DefaultRequestHeaders.Add("kpn", "undefined");
                    client.DefaultRequestHeaders.Add("Accept-Language", "zh-CN,zh-Hans;q=0.9");
                    client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate, br");
                    client.DefaultRequestHeaders.Add("Sec-Fetch-Mode", "cors");
                    client.DefaultRequestHeaders.Add("Trace-Id", "1.0.0.1739002116097.16");
                    client.DefaultRequestHeaders.Add("Origin", "https://app.kwaixiaodian.com");
                    client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 17_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Kwai/13.0.10.9095 MerchantWeb/1.0 ISLP/0 StatusHT/47 KDT/PHONE iosSCH/0 TitleHT/44 NetType/WIFI ISDM/0 ICFO/0 locale/zh-Hans CT/0 Yoda/3.0.7 ISLB/0 CoIS/2 ISLM/0 WebViewType/WK BHT/102 AZPREFIX/az2");
                    client.DefaultRequestHeaders.Add("Referer", "https://app.kwaixiaodian.com/page/kwaishop-cps-hybrid/recommend/leader/landing?layoutType=4&_refer=https%3A%2F%2Fapp.kwaixiaodian.com%2Fpage%2Fkwaishop-cps-hybrid%2Frecommend%2Fleader%2Fleader-goods");
                    //client.DefaultRequestHeaders.Add("Content-Length", "97");
                    client.DefaultRequestHeaders.Add("Connection", "keep-alive");
                    //client.DefaultRequestHeaders.Add("Content-Type", "application/x-www-form-urlencoded");
                    client.DefaultRequestHeaders.Add("Sec-Fetch-Dest", "empty");

                    //添加cookie，将 Cookie 信息作为一个字符串添加到请求头的 Cookie 字段中
                    var sbCookie = new StringBuilder();
                    foreach (var cookie in cookies)
                    {
                        sbCookie.AppendFormat("{0}={1}; ", cookie.Name, cookie.Value);
                    }
                    var cookieStr = sbCookie.ToString().TrimEnd(';').TrimEnd(' ');
                    client.DefaultRequestHeaders.Add("Cookie", cookieStr);

                    //设置请求体
                    var dicRequestBody = new Dictionary<string, string>();
                    dicRequestBody.Add("pcursor", pcursor);
                    dicRequestBody.Add("activityUserId", leaderId);
                    dicRequestBody.Add("keyWord", "");
                    dicRequestBody.Add("orderType", "0");
                    dicRequestBody.Add("hasCoupon", "0");
                    dicRequestBody.Add("channelId", channelId.ToString());
                    dicRequestBody.Add("priceStart", "0");
                    dicRequestBody.Add("priceEnd", "0");
                    dicRequestBody.Add("rateStart", "0");
                    dicRequestBody.Add("rateEnd", "0");
                    var content = new FormUrlEncodedContent(dicRequestBody);
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

                    GetProductInfoResponse getProductInfoResponse = null;
                    var response = client.PostAsync(requestUrl, content).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        Task<byte[]> t = response.Content.ReadAsByteArrayAsync();
                        if (t != null)
                        {
                            getProductInfoResponse = t.Result.GZipDecompress().FromJson<GetProductInfoResponse>();
                        }
                    }
                    else
                    {
                        //接口异常，获取错误详情信息
                        string errorDetails = response.Content.ReadAsStringAsync().Result;
                        if (!errorDetails.IsNullOrEmpty())
                        {
                            getProductInfoResponse = errorDetails.FromJson<GetProductInfoResponse>();
                            var errorMessage = string.Format("错误码：{0}，错误信息：{1}", getProductInfoResponse.code, getProductInfoResponse.error_msg);
                            apiResult.ErrorMessage = errorMessage;
                            return apiResult;
                        }
                    }

                    //cookie失效，result=109，code=G-803000-1002，error_msg=当前登录失效，请重新登录。
                    if (getProductInfoResponse != null && getProductInfoResponse.code == "G-803000-1002" && getProductInfoResponse.error_msg.Contains("登录失效"))
                    {
                        apiResult.ErrorMessage = "登录失效！";
                        return apiResult;
                    }

                    if (getProductInfoResponse == null
                        || getProductInfoResponse.result != 1
                        || getProductInfoResponse.itemList.Length == 0)
                    {
                        break;
                    }

                    var items = getProductInfoResponse.itemList.ToList();
                    foreach (var item in items)
                    {
                        var commissionRate = 0.00m;

                        //佣金率
                        commissionRate = (decimal)item.commissionRate / 100;

                        products.Add(new TProduct
                        {
                            CreatedBy = -1,
                            CreatedTime = now,
                            LastUpdatedBy = -1,
                            LastUpdatedTime = now,
                            LeaderId = leaderId,
                            ProductId = item.relItemId.ToString(),
                            Name = item.itemTitle,
                            ImageUrl = item.itemImgUrl,
                            Price = (decimal)item.reservePrice,
                            ProfitAmount = (decimal)item.profitAmount,
                            CommissionRate = commissionRate,
                            DeliveryTime = "",
                            PromoterNum = item.promoterNum,
                            SoldCountThirtyDays = item.soldCountThirtyDays,
                            DistributeItemId = item.distributeItemId.ToString(),
                            Status = (byte)Enums.ProductStatusType.OnStock,
                            HandleStatus = (byte)Enums.HandleStatusType.UnHandled,//默认未处理状态
                        });
                    }

                    //设置pcursor
                    pcursor = getProductInfoResponse.pcursor;

                    //每个请求之间间隔500毫秒
                    Thread.Sleep(millisecondsTimeout);
                }
            } while (!pcursor.IsNullOrEmpty());

            apiResult.ErrorCode = ErrorCodeConst.OK;
            apiResult.Data = products;
            return apiResult;
        }

        /// <summary>
        /// 获取商品详情，包括物流，店铺和统计数据等信息
        /// </summary>
        /// <param name="distributeItemId"></param>
        /// <returns></returns>
        public ApiResult<GetProductDetailInfoResponse> GetProductDetailInfo(string distributeItemId, int millisecondsTimeout = 500)
        {
            //https://app.kwaixiaodian.com/gateway/distribute/match/selection/decision/app/info
            ApiResult<GetProductDetailInfoResponse> apiResult = new ApiResult<GetProductDetailInfoResponse>();
            GetProductDetailInfoResponse getProductDetailInfoResponse = null;

            //获取配置
            var kwaiXiaoDianSection = _configuration.GetSection("KwaiXiaoDian");
            var kwaiXiaoDianHost = kwaiXiaoDianSection["ApiHost"].TrimEnd('/');

            //获取cookie
            var cookies = _cookieDao.Get(p => p.Domain == Consts.Domains.KwaiXiaoDian);
            if (!cookies.HasValue())
            {
                apiResult.ErrorMessage = "从数据库未获取到cookie！";
                return apiResult;
            }

            //构造POST请求，调用快手api
            var requestUrl = @"/gateway/distribute/match/selection/decision/app/info";

            //获取商品详情信息
            //使用HttpClient实现
            var baseAddress = new Uri(kwaiXiaoDianHost);
            using (var client = new HttpClient() { BaseAddress = baseAddress, Timeout = TimeSpan.FromSeconds(180) })
            {
                //添加request header
                client.DefaultRequestHeaders.Add("Host", "app.kwaixiaodian.com");
                client.DefaultRequestHeaders.Add("useRN", "1");
                client.DefaultRequestHeaders.Add("Accept", "application/json, text/plain, */*");
                client.DefaultRequestHeaders.Add("Sec-Fetch-Site", "same-origin");
                client.DefaultRequestHeaders.Add("Accept-Language", "zh-CN,zh-Hans;q=0.9");
                client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate, br");
                client.DefaultRequestHeaders.Add("Sec-Fetch-Mode", "cors");
                //client.DefaultRequestHeaders.Add("Content-Type", "application/json");
                client.DefaultRequestHeaders.Add("Origin", "https://app.kwaixiaodian.com");
                client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 17_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Kwai/13.1.10.9110 MerchantWeb/1.0 ISLP/0 StatusHT/47 KDT/PHONE iosSCH/0 TitleHT/44 NetType/WIFI ISDM/0 ICFO/0 locale/zh-Hans CT/0 Yoda/3.0.7 ISLB/0 CoIS/2 ISLM/0 WebViewType/WK BHT/102 AZPREFIX/az2");
                client.DefaultRequestHeaders.Add("Referer", "https://app.kwaixiaodian.com/page/kwaishop-cps-selection-decision-app?distributeItemId=538108053719&layoutType=4&_refer=https%3A%2F%2Fapp.kwaixiaodian.com%2Fpage%2Fkwaishop-cps-hybrid%2Frecommend%2Fleader%2Factivity_goods");
                //client.DefaultRequestHeaders.Add("Content-Length", "89");
                client.DefaultRequestHeaders.Add("Connection", "keep-alive");
                client.DefaultRequestHeaders.Add("Sec-Fetch-Dest", "empty");

                //添加cookie，将 Cookie 信息作为一个字符串添加到请求头的 Cookie 字段中
                var sbCookie = new StringBuilder();
                foreach (var cookie in cookies)
                {
                    sbCookie.AppendFormat("{0}={1}; ", cookie.Name, cookie.Value);
                }
                var cookieStr = sbCookie.ToString().TrimEnd(';').TrimEnd(' ');
                client.DefaultRequestHeaders.Add("Cookie", cookieStr);

                //设置请求体
                var requestData = new
                {
                    DistributeItemId = distributeItemId,
                    RelSceneCode = "CPS",
                    SceneCode = "selection_decision"
                };

                // 将对象序列化为JSON字符串
                // 配置JsonSerializerSettings
                JsonSerializerSettings settings = new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                };
                var json = JsonConvert.SerializeObject(requestData, settings);
                // 创建一个StringContent对象，用于包含请求体
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var response = client.PostAsync(requestUrl, content).Result;
                if (response.IsSuccessStatusCode)
                {
                    Task<byte[]> t = response.Content.ReadAsByteArrayAsync();
                    if (t != null)
                    {
                        getProductDetailInfoResponse = t.Result.GZipDecompress().FromJson<GetProductDetailInfoResponse>();
                    }
                }
                else
                {
                    //接口异常，获取错误详情信息
                    string errorDetails = response.Content.ReadAsStringAsync().Result;
                    if (!errorDetails.IsNullOrEmpty())
                    {
                        getProductDetailInfoResponse = errorDetails.FromJson<GetProductDetailInfoResponse>();
                        var errorMessage = string.Format("错误码：{0}，错误信息：{1}", getProductDetailInfoResponse.code, getProductDetailInfoResponse.error_msg);
                        apiResult.ErrorMessage = errorMessage;
                        return apiResult;
                    }
                }

                //cookie失效，result=109，code=G-803000-1002，error_msg=当前登录失效，请重新登录。
                if (getProductDetailInfoResponse != null && getProductDetailInfoResponse.code == "G-803000-1002" && getProductDetailInfoResponse.error_msg.Contains("登录失效"))
                {
                    apiResult.ErrorMessage = "登录失效！";
                    return apiResult;
                }

                //操作过快，风控拦截，result=2，code=G-808000-2，error_msg=操作过快，请稍后重试
                if (getProductDetailInfoResponse != null && getProductDetailInfoResponse.code == "G-808000-2" && getProductDetailInfoResponse.error_msg.Contains("操作过快"))
                {
                    Thread.Sleep(millisecondsTimeout);
                    apiResult.ErrorMessage = "操作过快，风控拦截！";
                    return apiResult;
                }

                //每个请求之间间隔
                Thread.Sleep(millisecondsTimeout);
            }

            apiResult.ErrorCode = ErrorCodeConst.OK;
            apiResult.Data = getProductDetailInfoResponse;
            return apiResult;
        }

        /// <summary>
        /// 获取商品达人排行榜信息
        /// </summary>
        /// <param name="distributeItemId">分发ID</param>
        /// <param name="productId">商品ID</param>
        /// <returns></returns>
        public ApiResult<IList<TProductRank>> GetProductRankInfo(string distributeItemId, string productId)
        {
            //https://ppg.m.etoote.com/rest/distribute/wireless/selection/ranking/top/seller/list?offset=0&size=50&id=0&distributeItemId=787441221761&_t=1739764755600
            ApiResult<IList<TProductRank>> apiResult = new ApiResult<IList<TProductRank>>();
            GetProductRankInfoResponse getProductRankInfoResponse = null;
            IList<TProductRank> productRanks = new List<TProductRank>();

            //读取配置
            var kwaiXiaoDianSection = _configuration.GetSection("KwaiXiaoDian");
            var etooteApiHost = kwaiXiaoDianSection["EtooteApiHost"].TrimEnd('/');

            //获取cookie
            var cookies = _cookieDao.Get(p => p.Domain == Consts.Domains.EtooteApi);
            if (!cookies.HasValue())
            {
                apiResult.ErrorMessage = "从数据库未获取到cookie！";
                return apiResult;
            }

            //构造GET请求，调用快手api，遍历获取全部页的数据
            var baseAddress = new Uri(etooteApiHost);
            using (var client = new HttpClient() { BaseAddress = baseAddress, Timeout = TimeSpan.FromSeconds(180) })
            {
                //添加request header
                client.DefaultRequestHeaders.Add("Host", "ppg.m.etoote.com");
                client.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest");
                client.DefaultRequestHeaders.Add("Sec-Fetch-Site", "same-origin");
                client.DefaultRequestHeaders.Add("Accept-Language", "zh-CN,zh-Hans;q=0.9");
                client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate, br");
                client.DefaultRequestHeaders.Add("Sec-Fetch-Mode", "cors");
                client.DefaultRequestHeaders.Add("Accept", "application/json, text/plain, */*");
                client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 17_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Kwai/13.1.10.9110 MerchantWeb/1.0 ISLP/0 StatusHT/47 KDT/PHONE iosSCH/0 TitleHT/44 NetType/WIFI ISDM/0 ICFO/0 locale/zh-Hans CT/0 Yoda/3.0.7 ISLB/0 CoIS/2 ISLM/0 WebViewType/WK BHT/102 AZPREFIX/az2");
                client.DefaultRequestHeaders.Add("Connection", "keep-alive");
                client.DefaultRequestHeaders.Add("Referer", "https://ppg.m.etoote.com/doodle/aAxwnXVs.html?distributeItemId=787441221761");
                client.DefaultRequestHeaders.Add("Sec-Fetch-Dest", "empty");

                //添加cookie，将 Cookie 信息作为一个字符串添加到请求头的 Cookie 字段中
                var sbCookie = new StringBuilder();
                foreach (var cookie in cookies)
                {
                    sbCookie.AppendFormat("{0}={1}; ", cookie.Name, cookie.Value);
                }
                var cookieStr = sbCookie.ToString().TrimEnd(';').TrimEnd(' ');
                client.DefaultRequestHeaders.Add("Cookie", cookieStr);

                DateTimeOffset now = DateTimeOffset.Now;
                long unixMilliseconds = now.ToUnixTimeMilliseconds();
                var requestUrl = string.Format("/rest/distribute/wireless/selection/ranking/top/seller/list?offset=0&size=50&id=0&distributeItemId={0}&_t={1}", distributeItemId, unixMilliseconds);
                var response = client.GetAsync(requestUrl).Result;
                if (response.IsSuccessStatusCode)
                {
                    Task<byte[]> t = response.Content.ReadAsByteArrayAsync();
                    if (t != null)
                    {
                        getProductRankInfoResponse = t.Result.GZipDecompress().FromJson<GetProductRankInfoResponse>();
                    }
                }
                else
                {
                    //接口异常，获取错误详情信息
                    string errorDetails = response.Content.ReadAsStringAsync().Result;
                    if (!errorDetails.IsNullOrEmpty())
                    {
                        getProductRankInfoResponse = errorDetails.FromJson<GetProductRankInfoResponse>();
                        var errorMessage = string.Format("错误码：{0}，错误信息：{1}", getProductRankInfoResponse.code, getProductRankInfoResponse.error_msg);
                        apiResult.ErrorMessage = errorMessage;
                        return apiResult;
                    }
                }

                //cookie失效，result=109，code=G-803000-1002，error_msg=当前登录失效，请重新登录。
                if (getProductRankInfoResponse != null && getProductRankInfoResponse.code == "G-803000-1002" && getProductRankInfoResponse.error_msg.Contains("登录失效"))
                {
                    apiResult.ErrorMessage = "登录失效！";
                    return apiResult;
                }

                if (getProductRankInfoResponse == null || getProductRankInfoResponse.result != 1)
                {
                    apiResult.ErrorMessage = "获取商品达人排行榜失败！";
                    return apiResult;
                }

                //返回结果
                if (getProductRankInfoResponse.data.HasValue())
                {
                    var list = getProductRankInfoResponse.data.ToList();
                    var now2 = DateTime.Now;
                    foreach (var item in list)
                    {
                        productRanks.Add(new TProductRank
                        {
                            CreatedBy = -1,
                            CreatedTime = now2,
                            LastUpdatedBy = -1,
                            LastUpdatedTime = now2,
                            ProductId = productId,
                            Rank = item.rank,
                            AuthorId = item.authorId.ToString(),
                            AuthorName = item.authorName,
                            AuthorHeadImg = item.authorHeadImg
                        });
                    }
                }

                //每个请求之间间隔
                Thread.Sleep(500);
            }

            apiResult.ErrorCode = ErrorCodeConst.OK;
            apiResult.Data = productRanks;
            return apiResult;
        }

        /// <summary>
        /// 获取商品SKU信息
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="millisecondsTimeout"></param>
        /// <returns></returns>
        public ApiResult<GetProductSkuInfoResponse> GetProductSkuInfo(string productId, int millisecondsTimeout = 500)
        {
            //https://app.kwaixiaodian.com/gateway/distribute/app/selection/sample/item/sku/list
            ApiResult<GetProductSkuInfoResponse> apiResult = new ApiResult<GetProductSkuInfoResponse>();
            GetProductSkuInfoResponse getProductSkuInfoResponse = null;

            var kwaiXiaoDianSection = _configuration.GetSection("KwaiXiaoDian");
            var kwaiXiaoDianHost = kwaiXiaoDianSection["ApiHost"].TrimEnd('/');
            var cookies = _cookieDao.Get(p => p.Domain == Consts.Domains.KwaiXiaoDian);
            if (!cookies.HasValue())
            {
                apiResult.ErrorMessage = "从数据库未获取到cookie！";
                return apiResult;
            }

            //构造POST请求，调用快手api
            var requestUrl = @"/gateway/distribute/app/selection/sample/item/sku/list";

            //获取商品详情信息
            //使用HttpClient实现
            var baseAddress = new Uri(kwaiXiaoDianHost);
            using (var client = new HttpClient() { BaseAddress = baseAddress, Timeout = TimeSpan.FromSeconds(180) })
            {
                //添加request header
                client.DefaultRequestHeaders.Add("Host", "app.kwaixiaodian.com");
                client.DefaultRequestHeaders.Add("useRN", "1");
                client.DefaultRequestHeaders.Add("Accept", "application/json, text/plain, */*");
                client.DefaultRequestHeaders.Add("Sec-Fetch-Site", "same-origin");
                client.DefaultRequestHeaders.Add("Accept-Language", "zh-CN,zh-Hans;q=0.9");
                client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate, br");
                client.DefaultRequestHeaders.Add("Sec-Fetch-Mode", "cors");
                //client.DefaultRequestHeaders.Add("Content-Type", "application/json");
                client.DefaultRequestHeaders.Add("Origin", "https://app.kwaixiaodian.com");
                client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 17_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Kwai/13.1.10.9110 MerchantWeb/1.0 ISLP/0 StatusHT/47 KDT/PHONE iosSCH/0 TitleHT/44 NetType/WIFI ISDM/0 ICFO/0 locale/zh-Hans CT/0 Yoda/3.0.7 ISLB/0 CoIS/2 ISLM/0 WebViewType/WK BHT/102 AZPREFIX/az2");
                client.DefaultRequestHeaders.Add("Referer", "https://app.kwaixiaodian.com/page/kwaishop-cps-selection-decision-app?distributeItemId=652030020536&layoutType=4&_refer=https%3A%2F%2Fapp.kwaixiaodian.com%2Fpage%2Fkwaishop-cps-hybrid%2Frecommend%2Fleader%2Factivity_goods");
                //client.DefaultRequestHeaders.Add("Content-Length", "89");
                client.DefaultRequestHeaders.Add("Connection", "keep-alive");
                client.DefaultRequestHeaders.Add("Sec-Fetch-Dest", "empty");

                //添加cookie，将 Cookie 信息作为一个字符串添加到请求头的 Cookie 字段中
                var sbCookie = new StringBuilder();
                foreach (var cookie in cookies)
                {
                    sbCookie.AppendFormat("{0}={1}; ", cookie.Name, cookie.Value);
                }
                var cookieStr = sbCookie.ToString().TrimEnd(';').TrimEnd(' ');
                client.DefaultRequestHeaders.Add("Cookie", cookieStr);

                //设置请求体
                var requestData = new
                {
                    ItemId = productId
                };

                // 将对象序列化为JSON字符串
                // 配置JsonSerializerSettings
                JsonSerializerSettings settings = new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                };
                var json = JsonConvert.SerializeObject(requestData, settings);
                // 创建一个StringContent对象，用于包含请求体
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var response = client.PostAsync(requestUrl, content).Result;
                if (response.IsSuccessStatusCode)
                {
                    Task<byte[]> t = response.Content.ReadAsByteArrayAsync();
                    if (t != null)
                    {
                        getProductSkuInfoResponse = t.Result.GZipDecompress().FromJson<GetProductSkuInfoResponse>();
                    }
                }
                else
                {
                    //接口异常，获取错误详情信息
                    string errorDetails = response.Content.ReadAsStringAsync().Result;
                    if (!errorDetails.IsNullOrEmpty())
                    {
                        getProductSkuInfoResponse = errorDetails.FromJson<GetProductSkuInfoResponse>();
                        var errorMessage = string.Format("错误码：{0}，错误信息：{1}", getProductSkuInfoResponse.result, getProductSkuInfoResponse.error_msg);
                        apiResult.ErrorMessage = errorMessage;
                        return apiResult;
                    }
                }

                //cookie失效，result=109，code=G-803000-1002，error_msg=当前登录失效，请重新登录。
                if (getProductSkuInfoResponse != null && getProductSkuInfoResponse.code == "G-803000-1002" && getProductSkuInfoResponse.error_msg.Contains("登录失效"))
                {
                    apiResult.ErrorMessage = "登录失效！";
                    return apiResult;
                }

                //操作过快，风控拦截，result=2，code=G-808000-2，error_msg=操作过快，请稍后重试
                if (getProductSkuInfoResponse != null && getProductSkuInfoResponse.code == "G-808000-2" && getProductSkuInfoResponse.error_msg.Contains("操作过快"))
                {
                    Thread.Sleep(millisecondsTimeout);
                    apiResult.ErrorMessage = "操作过快，风控拦截！";
                    return apiResult;
                }

                //每个请求之间间隔
                Thread.Sleep(millisecondsTimeout);
            }

            apiResult.ErrorCode = ErrorCodeConst.OK;
            apiResult.Data = getProductSkuInfoResponse;
            return apiResult;
        }

    }


    public static class StringExtension2
    {
        /// <summary>
        /// 字符串转int，转换失败返回Null
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int? ToIntOrNullAllowThousands(this string str)
        {
            return str.ToIntOrNullAllowThousands(null);
        }

        /// <summary>
        /// 字符串转int，转换失败返回可空
        /// </summary>
        /// <param name="str"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static int? ToIntOrNullAllowThousands(this string str, int? defaultValue)
        {
            int v;
            if (int.TryParse(str, System.Globalization.NumberStyles.AllowThousands, null, out v))
                return v;
            else
                return defaultValue;
        }
    }

}
